package com.df.happylearn.request;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

public class Utf8JsonRequest extends JsonRequest<JSONObject> {

    public boolean mIsAutoCache  =true;  //是否自动在客户端设置缓存时间
    public String uuid;

    public Utf8JsonRequest(String url, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
        super(0, url, (String)null, listener, errorListener);
    }

    public Utf8JsonRequest(String uuid, String url, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
        super(0, url, (String)null, listener, errorListener);
        this.uuid = uuid;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        HashMap<String, String> header = new HashMap<>();
        header.put("Client-UUid", uuid);
        return header;
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return super.getParams();
    }

    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String je = new String(response.data,"UTF-8");

            if(mIsAutoCache)
            {
                return Response.success(new JSONObject(je), CachedHttpHeaderParser.parseIgnoreCacheHeaders(response));
            }
            else
            {
                return Response.success(new JSONObject(je), HttpHeaderParser.parseCacheHeaders(response));
            }

        } catch (UnsupportedEncodingException var3) {
            return Response.error(new ParseError(var3));
        } catch (JSONException var4) {
            return Response.error(new ParseError(var4));
        }
    }

}
